import os
import json
import uuid
from flask import Blueprint, request, jsonify, send_from_directory, current_app
from werkzeug.utils import secure_filename
from app.services.grade_service import GradeService
from config import Config

bp = Blueprint('api', __name__)


@bp.route('/')
def index():
    return current_app.send_static_file('index.html')


@bp.route('/upload', methods=['POST'])
def upload_file():
    """处理文件上传"""
    try:
        if 'file' not in request.files:
            return jsonify({'error': '没有文件被上传'}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400

        if not file.filename.endswith('.xlsx'):
            return jsonify({'error': '只支持.xlsx格式的文件'}), 400

        # 生成唯一文件名
        filename = secure_filename(str(uuid.uuid4()) + '_' + file.filename)
        filepath = os.path.join(Config.UPLOAD_FOLDER, filename)
        file.save(filepath)

        # 处理自定义分值等级
        grade_levels = None
        grade_levels_json = request.form.get('gradeLevels')
        if grade_levels_json:
            try:
                grade_levels = json.loads(grade_levels_json)
            except json.JSONDecodeError:
                return jsonify({'error': '分值等级格式无效'}), 400

        # 读取Excel文件
        try:
            grades, errors = GradeService.read_as_details(filepath)

            # 如果有错误，返回错误信息
            if errors:
                return jsonify({
                    'success': False,
                    'errors': errors
                }), 400

            # 获取所有班级
            groups = sorted(list(set(grade.group_name for grade in grades if grade.group_name)))

            # 获取所有考试
            exams = sorted(list(set(grade.exam_code for grade in grades)))

            # 返回成功信息
            return jsonify({
                'success': True,
                'message': '文件上传成功',
                'filename': filename,
                'groups': groups,
                'exams': exams
            })

        except Exception as e:
            current_app.logger.error(f"处理Excel文件时出错: {str(e)}")
            return jsonify({'error': f'处理Excel文件时出错: {str(e)}'}), 500

        finally:
            # 清理上传的文件
            if os.path.exists(filepath):
                os.remove(filepath)

    except Exception as e:
        current_app.logger.error(f"上传文件时出错: {str(e)}")
        return jsonify({'error': f'上传文件时出错: {str(e)}'}), 500


@bp.route('/grades')
def grades_page():
    """成绩页面"""
    return current_app.send_static_file('grades.html')


@bp.route('/api/grades', methods=['POST'])
def save_grades():
    """保存成绩数据"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({'error': '没有提供数据'}), 400

        # 这里可以添加保存成绩的逻辑
        return jsonify({'success': True})
    except Exception as e:
        current_app.logger.error(f"保存成绩时出错: {str(e)}")
        return jsonify({'error': str(e)}), 500


@bp.route('/api/grades/<group>')
def get_grades(group):
    """获取成绩数据"""
    try:
        # 从文件或数据库中获取成绩数据
        # 这里需要实现具体的数据获取逻辑
        return jsonify({'success': True, 'data': []})
    except Exception as e:
        current_app.logger.error(f"获取成绩时出错: {str(e)}")
        return jsonify({'error': str(e)}), 500
